var NfcAdapter;

// NFC是否可用
function NFCEnabled() {
	var main = plus.android.runtimeMainActivity();
	NfcAdapter = plus.android.importClass('android.nfc.NfcAdapter');
	var nfcAdapter = NfcAdapter.getDefaultAdapter(main);
	return nfcAdapter.isEnabled()
}

// NFC初始化
function NFCInit() {
	var main = plus.android.runtimeMainActivity();
	var Intent = plus.android.importClass('android.content.Intent');
	var Activity = plus.android.importClass('android.app.Activity');
	var PendingIntent = plus.android.importClass('android.app.PendingIntent');
	var IntentFilter = plus.android.importClass('android.content.IntentFilter');
	NfcAdapter = plus.android.importClass('android.nfc.NfcAdapter');
	var nfcAdapter = NfcAdapter.getDefaultAdapter(main);
	var ndef = new IntentFilter('android.nfc.action.NDEF_DISCOVERED');
	var tag = new IntentFilter('android.nfc.action.TAG_DISCOVERED');
	var tech = new IntentFilter('android.nfc.action.TECH_DISCOVERED');
	var intentFiltersArray = [ndef, tag, tech];
	var techListsArray = [
		['android.nfc.tech.Ndef'],
		["android.nfc.tech.IsoDep"],
		["android.nfc.tech.NfcA"],
		["android.nfc.tech.NfcB"],
		["android.nfc.tech.NfcF"],
		["android.nfc.tech.Nfcf"],
		["android.nfc.tech.NfcV"],
		["android.nfc.tech.NdefFormatable"],
		["android.nfc.tech.MifareClassi"],
		["android.nfc.tech.MifareUltralight"]
	];
	
	var intent = new Intent(main, main.getClass());
	intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
	var pendingIntent = PendingIntent.getActivity(main, 0, intent, 0);
	nfcAdapter.enableForegroundDispatch(main, pendingIntent, IntentFilter, techListsArray);
}

// NFC读取数据
function NFCReadData() {
	var bind_code = null
	var main = plus.android.runtimeMainActivity();
	var runtimeIntent = main.getIntent();
	var action = runtimeIntent.getAction();
	
	if (NfcAdapter.ACTION_NDEF_DISCOVERED == action || NfcAdapter.ACTION_TAG_DISCOVERED == action || NfcAdapter.ACTION_TECH_DISCOVERED == action) {
		// bind_code = runtimeIntent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
		// bind_code = Bytes2HexString(bind_code);
		// console.log("bind_code:", bind_code)
		
		// return bind_code
		
		var Tag = plus.android.importClass('android.nfc.Tag');
		var bind_codes;
		var tagFromIntent = runtimeIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		console.log("TAG", tagFromIntent)
		var Ndef = plus.android.importClass("android.nfc.tech.Ndef")
		var ndef = Ndef.get(tagFromIntent)
		console.log("HHH", ndef)
		
		var NfcA = plus.android.importClass("android.nfc.tech.NfcA")
		console.log("NfcV", NfcA)
		var test_A = NfcA.get(tagFromIntent)
		console.log("get", test_A)
		test_A.close();
		test_A.connect();
		console.log("连接情况", test_A.isConnected())
		var tagUid = tagFromIntent.getId()
		tagUid = Bytes2HexString(tagUid);
		console.log("kkk", tagUid)
		
		bind_code = runtimeIntent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
		// ic卡号 进制转换 
		bind_codes = Bytes2HexString(bind_code);
		console.log("uuu", bind_codes)
		
		//使用NDEF读取有效记录
		var Parcelable = plus.android.importClass("android.os.Parcelable"); 
		var rawMsgs = runtimeIntent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
		var rawMsgs = runtimeIntent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
		
		if (rawMsgs != null) {
			console.log("读取MSG", rawMsgs) 
			console.log("MSG[0]",rawMsgs[0])
			try{
				var records = rawMsgs[0].getRecords();
				var result = records[0].getPayload();
				console.log("result",result)
				var s = plus.android.newObject("java.lang.String", result);  
				console.log(s); 
				
			}catch(e){
				console.log("错误:",e)
			}
		} else {
			console.log("非NDEF，无法读取MSG")
		}
	} else {
		return 'error'
	}
}

// NFC初始化type
function NFCInitType() {
	let bindCode = NFCReadData()
	if(bindCode) {
		uni.$emit('nfcType', {
			code: 'normal'
		})
	}
}

//将byte[]转为Hex
function Bytes2HexString(arrBytes) {
	var str = '';
	for (var i = 0; i < arrBytes.length; i++) {
		var tmp;
		var num = arrBytes[i];
		if (num < 0) {
			//Java中数值是以补码的形式存在的，应用程序展示的十进制是补码对应真值。补码的存在主要为了简化计算机底层的运算，将减法运算直接当加法来做
			tmp = (255 + num + 1).toString(16);
		} else {
			tmp = num.toString(16);
		}
		if (tmp.length == 1) {
			tmp = '0' + tmp;
		}
		str += tmp;
	}
	return str;
}

function readData() {  
	var main = plus.android.runtimeMainActivity();
	var intent = main.getIntent();
    var tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 
    var techList = tag.getTechList();  
    var bisMfc = false;  
    for(var i=0;i<techList.length;i++){  
        if(techList[i].indexOf('MifareClassic')>=0){  
            bisMfc=true;  
            break;  
        }  
    }  

    if(!bisMfc){  
        this.ICERROR='卡片类型错误!';  
        return;  
    }  

    var mfc=MifareClassic.get(tag);  
    if(!mfc){  
        this.ICERROR='卡片获取错误!';  
        return;  
    }  

    mfc.setTimeout(3000);  

    if(!mfc.isConnected()){  
        try{  
            invoke(mfc,'connect');   
        }catch(e){  
            this.ICERROR='卡片连接错误!';  
            return;  
        }  
    }  

    try{  
        this.ICUID=this.ByteArrayToHexString(tag.getId());  
        var cmdBytes=this.HexStringToByteArray(this.keyVal);  
        var auth=false;  
        if(this.keyType=="A"){  
            auth=invoke(mfc,"authenticateSectorWithKeyA",parseInt(this.sector),cmdBytes);  
        }else{  
            auth=invoke(mfc,"authenticateSectorWithKeyB",parseInt(this.sector),cmdBytes);  
        }  

        if(!auth){  
            this.ICERROR='扇区验证失败';  
            return;  
        }  

        var sectorData=[];  
        var tmpRet;  
        this.ICData='IC卡扇区数据>>';  

        for(var i=0;i<4;i++){   
            tmpRet=invoke(mfc,"readBlock",this.sector*4+i);  
            this.ICData=this.ICData+'\n';  
            this.ICData=this.ICData+this.ByteArrayToHexString(tmpRet);  
            sectorData.push.apply(sectorData,tmpRet);  
        }  

        console.log(this.ByteArrayToHexString(sectorData));  

        this.ICERROR='读卡完成';  

    }catch(e){  
        this.ICERROR=e.message;  
        console.error(e);   
    }finally{  
        mfc.close();  
    }  
}

export {
	NFCEnabled,
	NFCInit,
	NFCReadData,
	NFCInitType,
	readData
}